package com.yj.suncity.viewpager;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.yj.suncity.R;
import com.yj.suncity.activity.shouye.bean.ShouyeSuperadvBean;
import com.yj.suncity.activity.shouye.bean.SuperadvBean;
import com.yj.suncity.constant.URLCon;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ViewPagerScrollSuperadv {

	private ImageLoader imageLoader;
	private ViewPager pager;
	private int currentItem = 0; // 当前图片的索引号
	private int oldIndex = 0;//
	private List<SuperadvBean> list;
	private ScheduledExecutorService scheduledExecutorService;
	private LinearLayout lay_view_select;
	private Context context;
	private DisplayImageOptions options;
	private OnPagerClick onPagerClick;

	/**
	 * 自滚动的ViewPager
	 * 
	 * @param context
	 * @param imageLoader
	 * @param options
	 * @param pager
	 * @param lay_view_select
	 * @param list
	 */
	public ViewPagerScrollSuperadv(Context context, ImageLoader imageLoader,
			DisplayImageOptions options, ViewPager pager,
			LinearLayout lay_view_select, List<SuperadvBean> list,
			OnPagerClick onPagerClick) {
		super();
		this.imageLoader = imageLoader;
		this.pager = pager;
		this.list = list;
		this.lay_view_select = lay_view_select;
		this.context = context;
		this.options = options;
		this.onPagerClick = onPagerClick;
		setViewPager();

	}

	private void setViewPager() {

		for (int i = 0; i < list.size(); i++) {
			ImageView viewSelect = new ImageView(context);
			viewSelect.setImageResource(R.drawable.view_select_false);
			viewSelect.setPadding(6, 6, 6, 6);
			lay_view_select.addView(viewSelect);
			((ImageView) lay_view_select.getChildAt(0))
					.setImageResource(R.drawable.view_select_true);
		}

		pager.setAdapter(new MyPagerAdapter());

		pager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				//
				currentItem = arg0 % list.size();
				// 取消圆点选中
				((ImageView) lay_view_select.getChildAt(oldIndex))
						.setImageResource(R.drawable.view_select_false);
				// 圆点选中
				((ImageView) lay_view_select.getChildAt(currentItem))
						.setImageResource(R.drawable.view_select_true);

				oldIndex = currentItem;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		pager.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					startTimer();
				} else {
					stopTimer();
				}
				return false;
			}
		});

	}

	public void startTimer() {
		if (scheduledExecutorService == null
				|| scheduledExecutorService.isShutdown()) {
			scheduledExecutorService = Executors
					.newSingleThreadScheduledExecutor();
			// 当Activity显示出来后，每两秒钟切换一次图片显示
			scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1,
					2, TimeUnit.SECONDS);
		}
	}

	public void stopTimer() {
		// 当Activity不可见的时候停止切换
		if (scheduledExecutorService != null
				&& !scheduledExecutorService.isShutdown()) {
			scheduledExecutorService.shutdown();
			scheduledExecutorService = null;
		}
	}

	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			pager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};

	/**
	 * 换行切换任务
	 * 
	 * @author Administrator
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (pager) {
				/*
				 * if (viewPagerFlag) { if (currentItem <= 1) { viewPagerFlag =
				 * false; } currentItem = (currentItem - 1) % list.size();
				 * handler.obtainMessage().sendToTarget(); // 通过Handler切换图片 }
				 * else { if (currentItem >= (list.size() - 2)) { viewPagerFlag
				 * = true; } currentItem = (currentItem + 1) % list.size();
				 * handler.obtainMessage().sendToTarget(); // 通过Handler切换图片 }
				 */
				// if (currentItem >= list.size()) {
				// currentItem = 0;
				// }
				currentItem = (currentItem + 1) % list.size();
				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
		}

	}

	class MyPagerAdapter extends PagerAdapter {
		private LayoutInflater inflater;

		public MyPagerAdapter() {
			super();
			this.inflater = LayoutInflater.from(context);
			imageLoader = ImageLoader.getInstance();
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
			// super.destroyItem(container, position, object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			View imageLayout = inflater.inflate(R.layout.item_pager_image,
					container, false);
			ImageView imageView = (ImageView) imageLayout
					.findViewById(R.id.image);

			imageLoader.displayImage(URLCon.HOST
					+ list.get(position).getAdv_img(), imageView, options);
			//
			// final PicBean viewId = list.get(position);
			// viewPager的点击事件
			imageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					onPagerClick.onPagerClick(list.get(position).getAid(), list
							.get(position).getUserid());
				}
			});

			((ViewPager) container).addView(imageLayout, 0); // 将图片增加到ViewPager
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}

	public interface OnPagerClick {
		void onPagerClick(String advid, String adv_userid);
	}

}
